package com.better517na.stateprocess.run;

import com.better517na.stateprocess.model.OrderInfo;
import com.better517na.stateprocess.model.OrderStateEvent;
import com.better517na.stateprocess.model.ServiceResult;
import com.better517na.stateprocess.model.StateContext;
import com.better517na.stateprocess.state.StateProcessor;
import com.better517na.stateprocess.state.impl.AbstractStateProcessor;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Component
public class DefaultOrderFsmEngine implements OrderFsmEngine {

    @Resource(name = "defaultStateProcessRegistry")
    private DefaultStateProcessRegistry stateProcessorRegistry;
    @Override
    public <T> ServiceResult<T> sendEvent(OrderStateEvent orderStateEvent) throws Exception {
        OrderInfo fsmOrder = null;
        if (orderStateEvent.getNewCreated()) {
            //获取订单
            //fsmOrder = this.fsmOrderService.getFsmOrder(orderStateEvent.getOrderId());
            if (fsmOrder == null) {
                throw new Exception("未获取到订单信息");
            }
        }
        return sendEvent(orderStateEvent, fsmOrder);
    }

    @Override
    public <T> ServiceResult<T> sendEvent(OrderStateEvent orderStateEvent, OrderInfo fsmOrder) throws Exception {
        // 构造当前事件上下文
        StateContext context = this.getStateContext(orderStateEvent, fsmOrder);
        // 获取当前事件处理器
        StateProcessor<T,?> stateProcessor = this.getStateProcessor(context);
        // 执行处理逻辑
        return stateProcessor.action(context);
    }

    private <T> StateProcessor<T, ?> getStateProcessor(StateContext<?> context) throws Exception {
        OrderStateEvent stateEvent = context.getOrderStateEvent();
        OrderInfo fsmOrder = context.getOrderInfo();
        // 根据状态+事件对象获取所对应的业务处理器集合
        List<AbstractStateProcessor> processorList = stateProcessorRegistry.acquireStateProcess(fsmOrder.getOrderStatus(),
                stateEvent.getOrderStateEventEnum().getCode(), fsmOrder.getOrderScene(), fsmOrder.getOrderType());
        if (processorList == null) {
            // 订单状态发生改变
            if (!Objects.isNull(stateEvent.getOrderState()) && !stateEvent.getOrderState().equals(fsmOrder.getOrderStatus())) {
                throw new Exception("未找到状态实现类");
            }
            throw new Exception("未找到状态实现类");
        }
        if (CollectionUtils.isEmpty(processorList)) {
            throw new Exception("未找到状态实现类");
        }
        if (processorList.size() > 1) {
            throw new Exception("存在多个状态实现类");
        }
        return processorList.get(0);
    }
    private StateContext<?> getStateContext(OrderStateEvent orderStateEvent, OrderInfo fsmOrder) {
        StateContext<?> context = new StateContext(orderStateEvent, fsmOrder);
        return context;
    }
}

